/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ressources;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import modele.Database;
import modele.DatabaseManager;
import org.restlet.ext.xml.DomRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Delete;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.Put;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;

/**
 *
 * @author Théo
 */
public class LigneRessource extends ServerResource {

    private String dbName;
    private String tbName;
    private int noLine;
    Representation resultat;

    protected void doInit() throws ResourceException {
        // Get the "itemName" attribute value taken from the URI template
        // /items/{itemName}.
        this.dbName = (String) getRequest().getAttributes().get("dbName");
        this.tbName = (String) getRequest().getAttributes().get("tableName");
        this.noLine = Integer.parseInt(getRequest().getAttributes().get("idLine").toString())-1;

        Database.setConnectionData(dbName, "root", "");
        // Get the item directly from the "persistence layer".
        this.resultat = DatabaseManager.getRows(tbName);
        setExisting(this.resultat != null);
    }

    /** Représentation en réponse à une requête de méthode GET */
    @Get("text/xml")
    public Representation toXML() {
        System.out.println("GET row");
        return resultat;
    }

    /** Représentation en réponse à une requête de méthode PUT */
    @Put("text/xml")
    public void changeRow(Representation entity) {
        System.out.println("put row");
        if (getStatus().isSuccess()) {
            Document domParam;
            try {
                domParam = new DomRepresentation(entity).getDocument();
                NodeList fields = domParam.getElementsByTagName("field");
                String newValues = "";
                String oldValues = "";
                for (int i = 0; i < fields.getLength(); ++i) {
                    if (i != 0) {
                        newValues += ", ";
                        oldValues += " and ";
                    }
                    NamedNodeMap nnm = fields.item(i).getAttributes();
                    String colonne = nnm.getNamedItem("name").getNodeValue();
                    String oldValue = nnm.getNamedItem("oldValue").getNodeValue();
                    String newValue = fields.item(i).getFirstChild().getNodeValue();
                    newValues += colonne + "= \"" + newValue + "\"";
                    oldValues += colonne + "= \"" + oldValue + "\"";
                }

                String sql = "update " + tbName + " set " + newValues + " where " + oldValues;
                System.out.println(sql);
                Database db = Database.getInstance();
                db.write(sql);

            } catch (IOException ex) {
                Logger.getLogger(LigneRessource.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }

    /** Représentation en réponse à une requête de méthode DELETE */
    @Delete("text/xml")
    public void delRow() {
        System.out.println("delete row");

        String sql = "select * from " + tbName;
        System.out.println(sql);
        Database db = Database.getInstance();
        ResultSet rs = db.read(sql);
        String conditions = "";
        try {
            int i = 0;
            ResultSetMetaData rsmd = rs.getMetaData();
            int nbCol = rsmd.getColumnCount();
            while (rs != null && rs.next()) {
                if (rs.getRow() != noLine) {
                    for (int j = 1; j <= nbCol; ++j) {
                        if (j!=1){
                            conditions+= " and ";
                        }
                        String colonne = rs.getMetaData().getColumnName(j);
                        String value = rs.getString(j);
                        conditions += colonne + "=\"" + value + "\"";
                    }
                    break;
                }
            }


        } catch (SQLException ex) {
            Logger.getLogger(LigneRessource.class.getName()).log(Level.SEVERE, null, ex);
        }
        String sqlDel = "delete from " + tbName + " where " + conditions;
        System.out.println(sqlDel);
        db.write(sqlDel);
    }
}
